import openpyxl
from openpyxl.worksheet import worksheet
import os
import config
from utls import getCellValue

class Header:
    index = 0
    name = ""
    typeStr = ""
    note=""
    isFilter = False
    def __init__(self, worksheet:worksheet.Worksheet, index) -> None:
        self.index = index
        self.name = getCellValue(worksheet, 1, index)
        self.typeStr = getCellValue(worksheet, 2, index)
        self.note = getCellValue(worksheet, 3, index)
        self.isFilter = self.name == '' or self.name[0] == '#' or self.name[0].isdigit()
        pass

def getHeader(worksheet:worksheet.Worksheet):
    heads = []
    id = 0
    for i in range(1,worksheet.max_column + 1):
        head = Header(worksheet, i)
        if head.isFilter:
            continue
        heads.append(head)
        if "id" == head.name:
            id = i
    return heads, id

def generate(path):
    header:Header
    workbook = openpyxl.load_workbook(path, data_only=True)
    for name in workbook.sheetnames:

        if not name.isalpha():
            continue

        worksheet = workbook[name]
        headers, idIndex = getHeader(worksheet)
        if idIndex == 0:
            continue

        generateSharp(name, headers)

        tableLines = []
        idList = []
        for i in range(4, worksheet.max_row + 1):
            tableLine = []
            idCell = worksheet.cell(row = i, column = idIndex).value
            
            if idCell == None:
                continue

            if idCell in idList:
                print(str(idCell) +" duplication")
            
            idList.append(str(idCell))

            for header in headers:
                tableLine.append(getCellValue(worksheet, i, header.index))

            if len(tableLine) > 0:
                if len(''.join(tableLine).strip()) > 0:
                    tableLines.append('\t'.join(tableLine))
        
        if len(tableLines) > 0:
            savePath = os.path.join(config.csvOutput, name + ".csv")

            if not os.path.exists(config.csvOutput):
                os.makedirs(config.csvOutput)
            # save csv
            with open(savePath, "w+", encoding = 'utf-8') as f:
                names = []
                for header in headers:
                    names.append(header.name)
                f.write('\t'.join(names)+'\n')
                f.write('\n'.join(tableLines))

            print('generate: ' + savePath)

def generateSharp(tableName, headers):
    scriptLines=[]
    header:Header

    scriptLines.append('// The configuration generation file cannot be modified!\n')
    scriptLines.append('using UnityEngine;')
    scriptLines.append('public partial class {}'.format(tableName))
    scriptLines.append('{')

    for header in headers:
        if header.isFilter:
            continue
        scriptLines.append("\tpublic {} {}; // {}".format(header.typeStr, header.name, header.note))
    
    scriptLines.append('}')
    scriptLines.append('public partial class {0}Loader : BaseLoader<{0}>\n{{\n\n}}\n'.format(tableName))

    savePath = os.path.join(config.scriptOutput, tableName + "Loader.cs")
    dirName = os.path.dirname(savePath)
    if not os.path.exists(dirName):
        os.makedirs(dirName)
    
    # save script
    with open(savePath, "w+", encoding = 'utf-8') as f:
        f.write('\n'.join(scriptLines))
    print('generate: ' + savePath)



if __name__ == "__main__":

    print("csvPath:" + config.csvOutput)
    print("scriptPath:" + config.scriptOutput)

    for dir, _ ,files in os.walk("xlsxs"):
        for file in files:
            path = os.path.join(dir,file)
            generate(path)
